package com.leyou.upload.utils;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
//import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;


public class QiniuCloudUtil {


    private static final String ACCESS_KEY = "aObyrVTNwP0MP0kg0IyFrkB92q7cboWSZL4LggKn";
    private static final String SECRET_KEY = "Ua3zlnAE-2Tu99IRIAoyfCw3J4O1u-IB9dpSCFQu";
    // 要上传的空间名
    private static final String bucketname = "keelon";
    private static final String domain = "http://qiyi91hke.hn-bkt.clouddn.com/";       //外链域名
    // 密钥

    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);


    public static String upload(MultipartFile file1) throws IOException {



        String fileName = file1.getOriginalFilename();
        File file = new File(fileName);
        OutputStream out = null;
        try{
            //获取文件流，以文件流的方式输出到新文件
//    InputStream in = multipartFile.getInputStream();
            out = new FileOutputStream(file);
            byte[] ss = file1.getBytes();
            for(int i = 0; i < ss.length; i++){
                out.write(ss[i]);
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        // 创建上传对象，Zone*代表地区
        Configuration configuration = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(configuration);
        try {
            // 调用put方法上传

            String token = auth.uploadToken(bucketname);
            if(StringUtils.isEmpty(token)) {
                System.out.println("未获取到token，请重试！");
                return null;
            }
            String imageName = UUID.randomUUID().toString()+".png";
            System.out.println("File name = "+imageName);
            Response res = uploadManager.put(file,imageName,token);
            // 打印返回的信息
            if (res.isOK()){
                return domain+imageName;
            }
        }catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            e.printStackTrace();
            System.out.println("error "+r.toString());
            try {
                // 响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                System.out.println("error "+e1.error());
            }
        }
        return null;
    }

}
